package keeto.com.vn.bms.ui.activity;

import java.util.ArrayList;

import keeto.com.vn.bms.config.BMSCore;
import keeto.com.vn.bms.config.IBMSConfig;
import keeto.com.vn.bms.model.BMSUserModel;
import keeto.com.vn.bms.model.BasePopupModel;
import keeto.com.vn.bms.model.MsgHints;
import keeto.com.vn.bms.network.IBMSProtocol;
import keeto.com.vn.bms.service.BMSReceiver;
import keeto.com.vn.bms.ui.adapter.BasePopupAdapter;
import keeto.com.vn.bms.ui.fragment.ChatAdminFragment;
import keeto.com.vn.bms.ui.fragment.ChatDoctorFragment;
import keeto.com.vn.bms.ui.fragment.ChatManagerFragment;
import keeto.com.vn.bms.ui.widget.CallDialog;
import keeto.com.vn.bms.ui.widget.HomeChatHintsListener;
import keeto.com.vn.bms.ui.widget.HomeChatListDoctorListener;
import keeto.com.vn.bms.ui.widget.IPopupWindow;
import keeto.com.vn.bms.ui.widget.LogoutDialog;
import keeto.com.vn.bms.utils.BMSListener;
import keeto.com.vn.bms.utils.BMSSharedPreferences;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class BMSChatActivity extends FragmentActivity implements OnClickListener, OnItemClickListener{
	public final static String ACTION_READ_NOTIFY = "Read_Notify";
	public final static String ACTION_READ_MESSAGER = "Read_Messager";

	public static void actionLaunch(Context context) {
		Intent intent = new Intent(context, BMSChatActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_NO_ANIMATION);
		context.startActivity(intent);
	}

	private RelativeLayout rlTitleChat;
	private ImageButton btnChatLogin;
	private ImageButton btnChatMenu;
	private ImageButton btnChataddSurgery;

	private BMSSharedPreferences preferences;
	private LinearLayout llchatManager;
	private LinearLayout llchatAdmin;
	private LinearLayout llChatPhone;
	private LinearLayout llChatClear;
	private LinearLayout llChatHints;
	private LinearLayout llListdoctor;

	private FrameLayout frameChatManager;
	private FrameLayout frameChatAdmin;
	private FragmentManager manager;
	private FragmentTransaction transaction;

	private ChatManagerFragment chatManagerFragment;
	private ChatAdminFragment chatAdminFragment;
	private ChatDoctorFragment chatDoctorFragment;

	public static String sPhone = "com.android.contacts";
	public static String sKakao = "com.kakao.talk";
	public static String sSkype = "com.skype.raider";
	public static String sViber = "com.viber.voip";
	private ArrayList<Drawable> icons = new ArrayList<Drawable>();
	private ArrayList<String> names = new ArrayList<String>();
	private HomeChatListener listener = new HomeChatListener();

	private IPopupWindow popupHints;
	private ArrayList<MsgHints> mArrayList = new ArrayList<MsgHints>();
	private BasePopupAdapter popupAdapter;
	private ArrayList<BasePopupModel> arrPopup = new ArrayList<BasePopupModel>();
	private ListView lvPopup;

	private IPopupWindow popupListDoctor;
	private int GroupIDDoctor = 3;
	private	ArrayList<BMSUserModel> arrDoctor = new ArrayList<BMSUserModel>();
	private BasePopupAdapter popupDoctorAdapter;
	private ArrayList<BasePopupModel> arrDoctorPopup = new ArrayList<BasePopupModel>();
	private ListView lvDoctorPopup;
	private static int pageNumberDoctor = 1;
	private final static int PAGE_LIMIT = 10;
	private static boolean isloaded = false;
	private int With;
	private HomeChatHintsListener hintListener;
	private HomeChatListDoctorListener doctorListener;
	private String mAction = null;
	private Bundle bundle  = null;
	private String ObjID;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_chat_layout);
		preferences = new BMSSharedPreferences(this);
		manager = getSupportFragmentManager();
		transaction = manager.beginTransaction();
		Intent intent = getIntent();


		if (intent != null){
			if (intent.getAction() != null){
				mAction = intent.getAction();
				bundle = intent.getExtras();
			}
		}
		initUIComponent();
		initViewByPermisstion();
		registerReceiver();
		if (mAction != null && bundle != null){
			if (mAction.equals(ACTION_READ_NOTIFY)){
				ObjID = bundle.getString("NotifyId");
				BMSCore.getInstance(BMSChatActivity.this).taskSetReadNotify(ObjID, preferences.getUserAuthKey(this), listener);

			}else if (mAction.equals(ACTION_READ_MESSAGER)){
				ObjID = bundle.getString("MsgId");
				BMSCore.getInstance(BMSChatActivity.this).taskSetReadMessage(ObjID, preferences.getUserAuthKey(this), listener);
			}
		}

	}
	private void initUIComponent(){
		rlTitleChat = (RelativeLayout)findViewById(R.id.chat_title_layout);
		btnChatLogin = (ImageButton)findViewById(R.id.btn_home_login);
		btnChatMenu = (ImageButton)findViewById(R.id.btn_home_menu);
		btnChataddSurgery = (ImageButton)findViewById(R.id.btn_add_schedule); 
		frameChatManager = (FrameLayout)findViewById(R.id.realtabmanager);
		frameChatAdmin = (FrameLayout)findViewById(R.id.realtabAdmin);

		llchatManager = (LinearLayout)findViewById(R.id.ll_chat_manager);
		llchatAdmin = (LinearLayout)findViewById(R.id.ll_chat_admin);
		llListdoctor = (LinearLayout)findViewById(R.id.ll_list_doctor);
		llChatPhone = (LinearLayout)findViewById(R.id.ll_chat_phone);
		llChatClear = (LinearLayout)findViewById(R.id.ll_chat_clear); 
		llChatHints = (LinearLayout)findViewById(R.id.ll_chat_sms);

		btnChatLogin.setOnClickListener(this);
		btnChatMenu.setOnClickListener(this);
		btnChataddSurgery.setOnClickListener(this);
		llchatManager.setOnClickListener(this);
		llchatAdmin.setOnClickListener(this);
		llChatPhone.setOnClickListener(this);
		llChatClear.setOnClickListener(this);
		llChatHints.setOnClickListener(this);
		llListdoctor.setOnClickListener(this);
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		With = displaymetrics.widthPixels;
	}

	private void initViewByPermisstion(){
		switch (preferences.getUserPermission(this)) {
		case IBMSConfig.KEY_TYPE_LEADERSHIP:

			transaction = manager.beginTransaction();
			chatDoctorFragment = new ChatDoctorFragment();
			transaction.add(frameChatManager.getId(), chatDoctorFragment);
			transaction.commit();
			frameChatManager.setVisibility(View.VISIBLE);
			frameChatAdmin.setVisibility(View.GONE);
			btnChataddSurgery.setVisibility(View.GONE);
			llListdoctor.setVisibility(View.VISIBLE);
			llchatManager.setVisibility(View.GONE);
			llchatAdmin.setVisibility(View.GONE);
			llChatPhone.setVisibility(View.GONE);
			llChatHints.setVisibility(View.GONE);

			BMSCore.getInstance(this).taskGetTypeUser(preferences.getUserAuthKey(this),GroupIDDoctor,PAGE_LIMIT,pageNumberDoctor, listener);
			break;
		case IBMSConfig.KEY_TYPE_ADMIN:
			transaction = manager.beginTransaction();
			chatDoctorFragment = new ChatDoctorFragment();
			transaction.add(frameChatManager.getId(), chatDoctorFragment);
			transaction.commit();
			doctorListener = chatDoctorFragment.getListener();

			llListdoctor.setVisibility(View.VISIBLE);
			llchatManager.setVisibility(View.GONE);
			llchatAdmin.setVisibility(View.GONE);
			llChatPhone.setVisibility(View.GONE);
			llChatHints.setVisibility(View.GONE);
			BMSCore.getInstance(this).taskGetTypeUser(preferences.getUserAuthKey(this),GroupIDDoctor,PAGE_LIMIT,pageNumberDoctor, listener);

			break;
		case IBMSConfig.KEY_TYPE_DOCTOR:
			llListdoctor.setVisibility(View.GONE);
			chatManagerFragment = new ChatManagerFragment();
			transaction.add(frameChatManager.getId(), chatManagerFragment);
			chatAdminFragment = new ChatAdminFragment();
			transaction.add(frameChatAdmin.getId(), chatAdminFragment);
			transaction.commit();
			frameChatManager.setVisibility(View.GONE);
			frameChatAdmin.setVisibility(View.VISIBLE);
			llchatAdmin.setSelected(true);
			BMSCore.getInstance(this).taskGetChatHints(preferences.getUserAuthKey(this), listener);

			break;
		default:
			break;
		}
	}
	private void registerReceiver(){
		Intent intent = new Intent(BMSChatActivity.this,BMSReceiver.class);
		intent.setAction(BMSReceiver.BMSRECEIVER_INTENT);
		this.sendBroadcast(intent);
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.ll_chat_manager:
			llchatManager.setSelected(true);
			llchatAdmin.setSelected(false);
			transaction = manager.beginTransaction();
			transaction.show(chatManagerFragment);
			transaction.hide(chatAdminFragment);
			transaction.commit();
			frameChatManager.setVisibility(View.VISIBLE);
			frameChatAdmin.setVisibility(View.GONE);

			break;
		case R.id.ll_chat_admin:
			llchatAdmin.setSelected(true);
			llchatManager.setSelected(false);
			transaction = manager.beginTransaction();
			transaction.show(chatAdminFragment);
			transaction.hide(chatManagerFragment);
			transaction.commit();
			frameChatManager.setVisibility(View.GONE);
			frameChatAdmin.setVisibility(View.VISIBLE);
			break;
		case R.id.ll_chat_phone:
			icons.clear();
			getIcons();
			CallDialog callDialog = new CallDialog(this, icons, names);
			callDialog.show();
			break;
		case R.id.ll_list_doctor:
			showPopupListDoctor();
			break;
		case R.id.ll_chat_clear:
			DeleteMsgDialog  deleteMsgDialog = new DeleteMsgDialog(this);
			deleteMsgDialog.show();
			break;
		case R.id.ll_chat_sms:
			ShowPopupHints();
			break;
		case R.id.btn_home_login:
			if (preferences.getUserAuthKey(BMSChatActivity.this).equals("")){
				LoginBMSActivity.actionLaunch(BMSChatActivity.this);
			}else{
				LogoutDialog dialog = new LogoutDialog(BMSChatActivity.this);
				dialog.show();
			}
			break;
		case R.id.btn_home_menu:
			HomeBMSActivity.actionLaunch(this);
			break;
		case R.id.btn_add_schedule:
			CreateScheduleActivity.actionLaunch(this);

			break;

		default:
			break;
		}
	}


	public ArrayList<Drawable> getIcons() {

		try {
			Drawable iCallPhone;
			iCallPhone = getBaseContext().getPackageManager()
					.getApplicationIcon(sPhone);
			icons.add(iCallPhone);
			names.add("Phone");
		} catch (PackageManager.NameNotFoundException ne) {

		}
		try {
			Drawable iKakao;
			iKakao = getBaseContext().getPackageManager().getApplicationIcon(
					sKakao);
			icons.add(iKakao);
			names.add("KakaoTalk");
		} catch (PackageManager.NameNotFoundException ne) {

		}

		try {
			Drawable iSkype;
			iSkype = getBaseContext().getPackageManager().getApplicationIcon(
					sSkype);
			icons.add(iSkype);
			names.add("Skype");
			// bSkype = (ImageButton) findViewById(R.id.bSkype);
			// bSkype.setImageDrawable(iSkype);
		} catch (PackageManager.NameNotFoundException ne) {

		}

		try {
			Drawable iViber;
			iViber = getBaseContext().getPackageManager().getApplicationIcon(
					sViber);
			icons.add(iViber);
			names.add("Viber");
			// bViber = (ImageButton) findViewById(R.id.bViber);
			// bViber.setImageDrawable(iViber);
		} catch (PackageManager.NameNotFoundException ne) {

		}
		return icons;

	}

	class HomeChatListener extends BMSListener{
		
		@Override
		public void finishGetListHints(final int returnCode, String resultMsg,
				final ArrayList<MsgHints> arrayList) {
			// TODO Auto-generated method stub
			super.finishGetListHints(returnCode, resultMsg, arrayList);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (returnCode == IBMSProtocol.STATUS_CODE_OK && arrayList != null){						
						mArrayList.clear();
						mArrayList.addAll(arrayList);
						if (popupAdapter == null){
							for (int i=0;i<mArrayList.size();i++){
								arrPopup.add(new BasePopupModel(i, mArrayList.get(i).getContent(), Integer.parseInt(mArrayList.get(i).getId())));
							}
							popupAdapter = new BasePopupAdapter(BMSChatActivity.this, arrPopup);
							popupAdapter.notifyDataSetChanged();
						}else{
							popupAdapter.notifyDataSetChanged();
						}
					}
				}
			});
		}


		@Override
		public void finishGetTypeUsers(final int returnCode, String resultMsg,
				int recordNumber, final int countPage, int groupID,
				final ArrayList<BMSUserModel> listUserModel) {
			// TODO Auto-generated method stub
			super.finishGetTypeUsers(returnCode, resultMsg, recordNumber, countPage,
					groupID, listUserModel);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (returnCode == IBMSProtocol.STATUS_CODE_OK && listUserModel != null){
						if (pageNumberDoctor < countPage){
							pageNumberDoctor +=1;
						}else{
							arrDoctor.clear();
							pageNumberDoctor =-1;
						} 
						arrDoctor.addAll(listUserModel);
						for (int i=0;i<arrDoctor.size();i++){
							arrDoctorPopup.add(new BasePopupModel(i, arrDoctor.get(i).getFullName(),Integer.valueOf(arrDoctor.get(i).getUserID())));
						}
						if (popupDoctorAdapter == null){
							popupDoctorAdapter = new BasePopupAdapter(BMSChatActivity.this, arrDoctorPopup);
							popupDoctorAdapter.notifyDataSetChanged();
						}else{
							popupDoctorAdapter.notifyDataSetChanged();
						}
					}
				}
			});
		}
	}

	private OnItemClickListener itemListDoctor = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			if (doctorListener == null){
				doctorListener = chatDoctorFragment.getListener();
			}
			doctorListener.sendDoctorId(arrDoctorPopup.get(position).getKey()+"",arrDoctorPopup.get(position).getName());
			popupListDoctor.dismiss();

		}
	};

	private void showPopupListDoctor(){
		if (popupListDoctor == null){
			int popupWith = (int) (With*0.8f);
			popupListDoctor = new IPopupWindow(this, R.layout.popup_chat_layout, null, false, popupWith, LayoutParams.WRAP_CONTENT);
			TextView tvTitle = (TextView) popupListDoctor.getView().findViewById(R.id.tv_title_popup);
			lvDoctorPopup = (ListView)popupListDoctor.getView().findViewById(R.id.listPopup);
			lvDoctorPopup.setVisibility(View.VISIBLE);
			tvTitle.setText(this.getResources().getString(R.string.chat_list_doctor));
		}
		if (popupDoctorAdapter == null || arrDoctorPopup.size() ==0 ){
			if (arrDoctorPopup.size() == 0){
				BMSCore.getInstance(this).taskGetTypeUser(preferences.getUserAuthKey(this),GroupIDDoctor,PAGE_LIMIT,pageNumberDoctor, listener);

			}
			for (int i=0;i<arrDoctor.size();i++){
				arrDoctorPopup.add(new BasePopupModel(i, arrDoctor.get(i).getFullName(),i));
			}
			popupDoctorAdapter = new BasePopupAdapter(this, arrDoctorPopup);
		}
		lvDoctorPopup.setAdapter(popupDoctorAdapter);
		popupDoctorAdapter.notifyDataSetChanged();
		lvDoctorPopup.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				int lastInScreen = firstVisibleItem + visibleItemCount; 
				if((lastInScreen == totalItemCount) && (pageNumberDoctor >0) && !isloaded){
					BMSCore.getInstance(BMSChatActivity.this).taskGetTypeUser(preferences.getUserAuthKey(BMSChatActivity.this),GroupIDDoctor,PAGE_LIMIT,pageNumberDoctor, listener);
					isloaded = true;
				}
			}
		});
		lvDoctorPopup.setOnItemClickListener(itemListDoctor);
		popupListDoctor.setAutoHideOutside();
		popupListDoctor.showAsDropDown(rlTitleChat, llListdoctor.getMeasuredWidth(), 0);
	}

	private void ShowPopupHints(){
		if (popupHints == null){
			int popupWith = (int) (With*0.8f);
			popupHints = new IPopupWindow(this, R.layout.popup_chat_layout, null, false, popupWith, LayoutParams.WRAP_CONTENT);
			TextView tvTitle = (TextView) popupHints.getView().findViewById(R.id.tv_title_popup);
			lvPopup = (ListView)popupHints.getView().findViewById(R.id.listPopup);
			lvPopup.setVisibility(View.VISIBLE);
			tvTitle.setText(this.getResources().getString(R.string.chat_sms));
		}
		if (popupAdapter == null || mArrayList.size() == 0){
			if (mArrayList.size() == 0){
				BMSCore.getInstance(this).taskGetChatHints(preferences.getUserAuthKey(this), listener);
			}
			for (int i=0;i<mArrayList.size();i++){
				arrPopup.add(new BasePopupModel(i, mArrayList.get(i).getContent(), Integer.parseInt(mArrayList.get(i).getId())));
			}
			popupAdapter = new BasePopupAdapter(this, arrPopup);
		}
		lvPopup.setAdapter(popupAdapter);
		popupAdapter.notifyDataSetChanged();
		lvPopup.setOnItemClickListener(this);
		popupHints.setAutoHideOutside();
		popupHints.showAsDropDown(rlTitleChat, llchatManager.getMeasuredWidth(), 0);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		popupHints.dismiss();
		if (frameChatAdmin.getVisibility() == View.GONE){
			hintListener = chatManagerFragment.getListener();
		}else{
			hintListener = chatAdminFragment.getListener();
		}
		hintListener.sendMsgHint(arrPopup.get(position).getName());


	}
	public class DeleteMsgDialog extends Dialog implements android.view.View.OnClickListener {

		private Context ctx;
		private Button btnOk;
		private Button btnCancel;
		private BMSSharedPreferences preferences;
		private LinearLayout llParent;
		private TextView tvTitle;
		private TextView tvContent;
		public DeleteMsgDialog(Context context) {
			super(context);
			this.ctx = context;
			this.preferences = new BMSSharedPreferences(context);
		}


		protected DeleteMsgDialog(Context context, boolean cancelable,
				OnCancelListener cancelListener) {
			super(context, cancelable, cancelListener);
			// TODO Auto-generated constructor stub
		}

		public DeleteMsgDialog(Context context, int theme) {
			super(context, theme);
			// TODO Auto-generated constructor stub

		}

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onCreate(savedInstanceState);
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			setContentView(R.layout.logout_dialog_layout);
			llParent = (LinearLayout)findViewById(R.id.parent_logout_dialog);
			tvTitle  = (TextView)findViewById(R.id.tvTitleDialog);
			tvContent = (TextView)findViewById(R.id.tvContentDialog);

			btnOk = (Button)findViewById(R.id.btn_ok_logout);
			btnCancel = (Button)findViewById(R.id.btn_cancel_logout);

			tvTitle.setText(ctx.getResources().getString(R.string.title_delete_msg));
			tvContent.setText(ctx.getResources().getString(R.string.content_delete_msg));
			btnOk.setOnClickListener(this);
			btnCancel.setOnClickListener(this);
			this.setCanceledOnTouchOutside(true);
			Rect displayRectangle = new Rect();
			Window window = this.getWindow();
			window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
			llParent.setMinimumWidth((int) (displayRectangle.width()* 0.9f));
		}

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btn_ok_logout:
				if (preferences.getUserPermission(ctx) == IBMSConfig.KEY_TYPE_DOCTOR){
					if (frameChatAdmin.getVisibility() == View.GONE){
						hintListener = chatManagerFragment.getListener();
							hintListener.deletemsgManager();
					}else{
						hintListener = chatAdminFragment.getListener();
						hintListener.deletemsgAdmin();
					}
				}else if (preferences.getUserPermission(ctx) == IBMSConfig.KEY_TYPE_LEADERSHIP){
					doctorListener = chatDoctorFragment.getListener();
					doctorListener.deleteMsg();
				}else  if (preferences.getUserPermission(ctx) == IBMSConfig.KEY_TYPE_ADMIN){
					doctorListener = chatDoctorFragment.getListener();
					doctorListener.deleteMsg();
				}
				this.dismiss();
				break;
			case R.id.btn_cancel_logout:
				this.dismiss();
				break;

			default:
				break;
			}
		}
	}
}
